package ooo.reindeer.concurrent.netqueue.message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import ooo.reindeer.data.util.ByteDataUtil;
import ooo.reindeer.logging.ILogger;
import ooo.reindeer.logging.LogUtil;

import java.util.List;

public class MessageCoder extends ByteToMessageCodec<Message> {

    private static final ILogger logger = LogUtil.getLogger(MessageCoder.class);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("decode {}", ByteDataUtil.getHexDump(byteBuf));
        }
        Message message = ByteDataUtil.toObject(byteBuf, Message.class);
        list.add(message);
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message o, ByteBuf byteBuf) throws Exception {

        ByteDataUtil.writeByteBuf(byteBuf, o);
        if (logger.isDebugEnabled()) {
            logger.debug("encode {}", ByteDataUtil.getHexDump(byteBuf));
        }

    }
}
